//
//  ViewController.m
//  xinlikangkaizha
//
//  Created by admin-zxw on 2021/2/23.
//

#import "ViewController.h"
#import <AFNetworking/AFNetworking.h>
#import <TFHpple/TFHpple.h>
#import <SDWebImage/UIImageView+WebCache.h>
#import <Masonry/Masonry.h>
#import "XWPickerView.h"
#import "UIView+Toast.h"
#import <Flutter/Flutter.h>

// 防止多次调用
#define kPreventRepeatClickTime(_seconds_) \
static BOOL shouldPrevent; \
if (shouldPrevent) return; \
shouldPrevent = YES; \
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)((_seconds_) * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{ \
shouldPrevent = NO; \
}); \

//--------------------------ABOUT COLOR 颜色相关 -------------------------
//RGB转UIColor（不带alpha值）
#define UIColorFromRGB(rgbValue) [UIColor  colorWithRed:((float)((rgbValue & 0xFF0000) >> 16))/255.0  green:((float)((rgbValue & 0xFF00) >> 8))/255.0  blue:((float)(rgbValue & 0xFF))/255.0 alpha:1.0]
//RGB转UIColor（带alpha值）
#define UIColorFromRGBWithAlpha(rgbValue,a) [UIColor  colorWithRed:((float)((rgbValue & 0xFF0000) >> 16))/255.0  green:((float)((rgbValue & 0xFF00) >> 8))/255.0  blue:((float)(rgbValue & 0xFF))/255.0 alpha:a]

#define FloorKey @"FloorKey"

@interface ViewController ()
@property (weak, nonatomic) IBOutlet UIImageView *imageView;
@property (nonatomic,strong) UILabel *floorLab;
@property (weak, nonatomic) IBOutlet UILabel *timeOutLab;
@property (nonatomic,strong) UIWindow *window;

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    UIView *bgView = [[UIView alloc]init];
    bgView.backgroundColor = UIColorFromRGB(0xe6e6e6);
    bgView.layer.cornerRadius = 5;
    [self.view addSubview:bgView];
    [bgView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.mas_equalTo(self.view);
        make.top.mas_equalTo(UIApplication.sharedApplication.statusBarFrame.size.height+100);
        make.width.mas_equalTo(100);
        make.height.mas_equalTo(40);
    }];
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(selectFloor)];
    [bgView addGestureRecognizer:tap];
    
    UIImageView *imgView = [[UIImageView alloc]init];
    imgView.image = [UIImage imageNamed:@"arrow"];
    [bgView addSubview:imgView];
    [imgView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.mas_equalTo(-10);
        make.centerY.mas_equalTo(bgView);
        make.size.mas_equalTo(18);
    }];
    
    self.floorLab = [UILabel new];
    self.floorLab.textColor = UIColorFromRGB(0x555555);
    self.floorLab.textAlignment = NSTextAlignmentCenter;
    self.floorLab.font = [UIFont systemFontOfSize:15];
    [bgView addSubview:self.floorLab];
    [self.floorLab mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(10);
        make.right.mas_equalTo(imgView.mas_left).offset(-10);
        make.centerY.mas_equalTo(bgView);
    }];
    
    self.timeOutLab.hidden = YES;
    
    NSString *floorKey = [[NSUserDefaults standardUserDefaults] stringForKey:FloorKey];
    if (floorKey==nil) {
        //默认是30楼
        floorKey = @"30";
    }
    self.floorLab.text = [NSString stringWithFormat:@"%@楼",floorKey];
    [self httpRequest:floorKey];
}

-(void)httpRequest:(NSString*)floor{
    
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObject:@"text/html"];
    [manager.requestSerializer setValue:@"openid=oR9ra0zJAA0IwxZ84Rhy2csUIrow; session_id=5d9ef78b47c2a" forHTTPHeaderField:@"Cookie"];
    [manager.requestSerializer setValue:@"Mozilla/5.0 (iPhone; CPU iPhone OS 13_1_2 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Mobile/15E148 MicroMessenger/7.0.8(0x17000820) NetType/WIFI Language/zh_CN" forHTTPHeaderField:@"User-Agent"];
    
    NSString *url = [NSString stringWithFormat:@"http://face.xinlikang.cn/yuyue/index.php?controller=home&action=qrcode&floor_id=%@",floor];
    [manager GET:url parameters:nil headers:nil progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        NSString *data = [[NSString alloc]initWithData:responseObject encoding:NSUTF8StringEncoding];
        NSLog(@"%@",data);
        
        TFHpple *xpathParser = [[TFHpple alloc]initWithHTMLData:responseObject];
        // 根据标签进行筛选 获取所有标签是<span>的代码块
        NSArray *elements  = [xpathParser searchWithXPathQuery:@"//img"];
        //开始整理数据
        for (TFHppleElement *elsement in elements) {
            if ([elsement content] != nil) {
                NSLog(@"%@",[elsement objectForKey:@"style"]);
                if ([[elsement objectForKey:@"style"]isEqualToString:@"width:250px;height:250px"]) {//筛选属性是里有style 并且值是text-align的标签
                    
                    //打印出该节点的所有内容  包括标签
                    NSLog(@"%@",elsement.raw);
                    NSString *image = elsement.attributes[@"src"];
                    NSLog(@"%@",image);
                    [self.imageView sd_setImageWithURL:[NSURL URLWithString:image]];
                    self.timeOutLab.hidden = NO;
                }
            }
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        [self.view makeToast:@"二维码获取失败" duration:1 position:CSToastPositionCenter style:[[CSToastStyle alloc] initWithDefaultStyle]];
    }];
    
}
- (IBAction)refreshAction:(id)sender {
    
    kPreventRepeatClickTime(3);
    
    NSString *floor = [self.floorLab.text substringToIndex:self.floorLab.text.length-1];
    [self httpRequest:floor];
}

-(void)selectFloor{
    
    XWPickerView *pickerView = [[XWPickerView alloc]initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, 250)];
    [pickerView reloadDataWithArray:@[@"21楼",@"25楼",@"26楼",@"27楼",@"28楼",@"29楼",@"30楼",@"31楼"]];
    [pickerView showWithViewController:self];
    [pickerView setDidClickSureBtnBlock:^(NSString * _Nonnull selectItem, NSInteger index) {
        NSString *floorStr = [selectItem substringToIndex:selectItem.length-1];
        self.floorLab.text = selectItem;
        [self httpRequest:floorStr];
        //存储
        [[NSUserDefaults standardUserDefaults] setValue:floorStr forKey:FloorKey];
    }];
}

- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
    FlutterViewController *flutterViewController = [[FlutterViewController alloc]initWithProject:nil initialRoute:@"detail?{\"message\":\"嗨，本文案来自第一个原生页面，将在Flutter页面看到我\"}" nibName:nil bundle:nil];
    [self.navigationController pushViewController:flutterViewController animated:YES];
}

@end
